import TimeDataMgr from "./TimeDataMgr";
import EventMgr from "./EventMgr";
import NativeEventType from "./NativeEventType";
import EngineUtil from "./EngineUtil";

const { ccclass, property } = cc._decorator;

@ccclass
export default class TimeDataSys extends TimeDataMgr {
    private static _instance: TimeDataSys;
    private pauseTimeStamp: number;
    private prevPauseTime: number;
    private game_start_timeStamp: number;

    constructor() {
        super();
        EventMgr.listen(NativeEventType.APP_PAUSE, this.appPause, this);
        EventMgr.listen(NativeEventType.APP_RESTART, this.appRestart, this);
    }

    public static _getInstance(): TimeDataSys {
        if (!TimeDataSys._instance) {
            TimeDataSys._instance = new TimeDataSys();
        }
        return TimeDataSys._instance;
    }

    public appPause(): void {
        this.pauseTimeStamp = EngineUtil.getTimeStamp();
    }

    public appRestart(): void {
        const e = EngineUtil.getTimeStamp();
        if (this.pauseTimeStamp !== 0) {
            this.prevPauseTime = e - this.pauseTimeStamp;
            this.pauseTimeStamp = 0;
            this.updateGameTimeStamp();
        }
    }

    public resetGameTime(): void {
        this.game_start_timeStamp = EngineUtil.getTimeStamp();
    }

    public getGameTime(): number {
        return EngineUtil.getTimeStamp() - this.game_start_timeStamp;
    }

    public updateGameTimeStamp(): void {
        this.game_start_timeStamp += this.prevPauseTime;
    }
}
